//
//  OrderViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/13.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "OrderViewController.h"
#import "OrderCell.h"
#import "OrderDetailViewController.h"
#import "OrderPayViewController.h"
#import "MyProductViewController.h"

@interface OrderViewController () <UITableViewDataSource, UITableViewDelegate, OrderDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;
@property (assign, nonatomic) NSInteger index;
@property (assign ,nonatomic) BOOL ifAllSelected;
@property (weak, nonatomic) IBOutlet UIButton *allSelectedButton;
@property (assign, nonatomic) BOOL ifEdit;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewToBottom;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (strong, nonatomic) NSArray *jsonArray;
@property (strong, nonatomic) NSMutableDictionary *dict;
//@property (assign, nonatomic) NSInteger orderCount;
@property (strong, nonatomic) BulkorderModel *bulkorderModel;
@property (strong, nonatomic) ShoppingCartModel *buyModel;//购买的产品
@property (strong, nonatomic) NSString *position;

@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ifEdit = NO;
    [self titleView:@"大货下单"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(edit)];
    _index = 4;
    if (self.ifTab) {
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.frame.size.height - 47);
        self.navigationItem.leftBarButtonItem = nil;
        self.viewToBottom.constant = 44;
    }
    self.bottomView.hidden = self.index?0:!0;
    _dict = [NSMutableDictionary dictionary];
    _allSelectedButton.hidden = YES;
//    _orderCount = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
//    [self.myTableView reloadData];
    _position = @"";
    self.totalPrice.text = @"合计:￥0.00";
    _allSelectedButton.selected = NO;
    _ifAllSelected = NO;
}

- (void)requestData {
    if (![UserModel sharedInstance].userName) {
        [self.navigationController pushViewController:[LoginViewController new] animated:YES];
        return;
    }
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData queryShoppingCartList:[UIUtil toJsonString:dic] withBlock:^(NSArray *jsonArray, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.jsonArray = jsonArray;
            [self.myTableView reloadData];
        }
    }];
}

#pragma mark - action Methods
- (IBAction)chooseMyProduct:(id)sender {
    MyProductViewController *view = [[MyProductViewController alloc] init];
    view.hidesBottomBarWhenPushed = YES;
    view.ifOrder = YES;
    [self.navigationController pushViewController:view animated:YES];
}

//- (IBAction)allSelected:(id)sender {
//    _ifAllSelected = !_ifAllSelected;
//    _allSelectedButton.selected = _ifAllSelected;
//    [self.myTableView reloadData];
//    // 合计总价
//    CGFloat price = 0.00;
//    if (_ifAllSelected) {
//        for (int i=0; i<self.jsonArray.count; i++) {
//            ShoppingCartModel *model = self.jsonArray[i];
//            price = price + [model.totalPrice floatValue];
//            [_dict setValue:model forKey:@"i"];
//        }
//    }
//    [_dict removeAllObjects];
//    self.totalPrice.text = [NSString stringWithFormat:@"合计:￥%.2f",price];
//}

- (IBAction)goToBalance:(id)sender {
    if ([[self.totalPrice.text substringFromIndex:4] isEqualToString:@"0.00"]) {
        [[ESHUDView sharedInstance] showErrorMessage:@"还没有选择产品" dismissBlock:nil];
        return;
    }
    [ESHUDView showLoading];
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"shoppingcartId":_buyModel.id==nil?@"":_buyModel.id};
    [RequestData queryShoppingCartParameters:[UIUtil toJsonString:dic] withBlock:^(BulkorderModel *model, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            self.bulkorderModel = model;
        }
    }];
}

- (void)setBulkorderModel:(BulkorderModel *)bulkorderModel {
    _bulkorderModel = bulkorderModel;
    NSArray *array = [[NSArray alloc] initWithArray:_bulkorderModel.numList];
    _bulkorderModel.numList = nil;
    _bulkorderModel.imageList = nil;
    _bulkorderModel.mainImage = nil;
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                          @"token":[UserModel sharedInstance].userToken,
                          @"SCRecord":@{ @"productId":_bulkorderModel.productId==nil?@"":_bulkorderModel.productId,
                                         @"productName":_bulkorderModel.productName==nil?@"":_bulkorderModel.productName,
                                         @"totalQuantity":_bulkorderModel.totalQuantity==nil?@"":_bulkorderModel.totalQuantity,
                                         @"perPrice":_bulkorderModel.perPrice==nil?@"":_bulkorderModel.perPrice,
                                         @"totalPrice":_bulkorderModel.totalPrice==nil?@"":_bulkorderModel.totalPrice,
                                         @"requiredExplain":_bulkorderModel.requiredExplain==nil?@"":_bulkorderModel.requiredExplain,
                                         @"deliveryTime":_bulkorderModel.deliveryTime==nil?@"":_bulkorderModel.deliveryTime,
                                         @"deliveryWay":_bulkorderModel.deliveryWay==nil?@"":_bulkorderModel.deliveryWay,
                                         @"userReceiveAddress":_bulkorderModel.userReceiveAddress==nil?@"":_bulkorderModel.userReceiveAddress},
                          @"dataList":array==nil?@"":array};
    [RequestData bulkorderParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *bulkorderId, NSString *toPayId, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交大货单失败":msg dismissBlock:nil];
            }
            //            _orderCount = 0;
            //            [_orderArray removeAllObjects];
            //            [[AFAPIClient sharedClient].operationQueue cancelAllOperations];
        } else {
            //            _orderCount = _orderCount + 1;
            //            if (_orderCount == self.orderArray.count) {
            [ESHUDView dismiss];
            OrderPayViewController *view = [[OrderPayViewController alloc] init];
            view.toPayId = toPayId;
            [self.navigationController pushViewController:view animated:YES];
            //            }
        }
    }];
}

- (void)edit {
    self.ifEdit = !self.ifEdit;
    if (self.ifEdit) {
        self.navigationItem.rightBarButtonItem.title = @"完成";
    } else {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"orderEdit" object:[NSString stringWithFormat:@"%d",self.ifEdit]];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.jsonArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *orderCellIdentifier = @"OrderCell";
    [self.myTableView registerNib:[UINib nibWithNibName:@"OrderCell" bundle:nil]
           forCellReuseIdentifier:orderCellIdentifier];
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:orderCellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[OrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderCellIdentifier];
    }
    cell.model = [_jsonArray objectAtIndex:indexPath.row];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.ifSelected = NO;
    cell.ifEdit = _ifEdit;
    if ([_position isEqualToString:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]) {
        cell.ifSelected = YES;
        self.totalPrice.text = [NSString stringWithFormat:@"合计:￥%.2f",[cell.model.totalPrice floatValue]];
    }
    //    cell.ifSelected = _ifAllSelected;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - OrderDelegate
- (void)didSelectDeleteAtIndexPath:(NSIndexPath *)indexPath {
    ShoppingCartModel *model = [self.jsonArray objectAtIndex:indexPath.row];
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                          @"token":[UserModel sharedInstance].userToken,
                          @"type":@"0",
                          @"SCRecord":@{ @"id":model.id,
                                         @"productId":model.productId,
                                         @"productName":model.productName,
                                         @"totalQuantity":model.totalQuantity,
                                         @"perPrice":model.perPrice,
                                         @"totalPrice":model.totalPrice,
                                         @"requiredExplain":model.requiredExplain,
                                         @"deliveryTime":model.deliveryTime,
                                         @"deliveryWay":model.deliveryWay,
                                         @"remark":@""},
                          @"dataList":@[]};
    [RequestData addShoppingCart:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"删除订单失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
            NSMutableArray *array = [NSMutableArray arrayWithArray:self.jsonArray];
            [array removeObjectAtIndex:indexPath.row];
            self.jsonArray = array;
            [self.myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
            if ([_position isEqualToString:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]) {
                self.totalPrice.text = @"合计:￥0.00";
            }
        }
    }];
}

- (void)didSelectModifyAtIndexPath:(NSIndexPath *)indexPath {
    OrderDetailViewController *view = [[OrderDetailViewController alloc] init];
    view.ifPay = NO;
    view.orderTitle = @"修改订单";
    view.shoppingcartId = ((ShoppingCartModel *)[self.jsonArray objectAtIndex:indexPath.row]).id;
    view.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (void)didSelectCheckButtonAtIndexPath:(NSIndexPath *)indexPath ifcheck:(BOOL)ifcheck {
    // 合计总价
    if (ifcheck) {
        _buyModel = [self.jsonArray objectAtIndex:indexPath.row];
        self.totalPrice.text = [NSString stringWithFormat:@"合计:￥%.2f",[_buyModel.totalPrice floatValue]];
        _position = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        [self.myTableView reloadData];
    } else {
        self.totalPrice.text = @"合计:￥0.00";
    }
}

@end
